package com.it.water.controller.HttpController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.water.common.Result;
import com.it.water.controller.HttpController.dto.LoginDTO;
import com.it.water.controller.HttpController.request.LoginRequest;
import com.it.water.entity.User;
import com.it.water.service.impl.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 *
 * @author <a href="mailto:2038322151@qq.com">Miraitowa_zcx</a>
 * @author HelloWord505
 * @version 1.0
 * @since 2024-03-17
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    /**
     * 用户服务
     */
    private final UserService userService;

    /**
     * 注入用户服务
     *
     * @param userService 用户服务
     */
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户注册
     *
     * @param user 用户对象
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<LoginDTO> register(@RequestBody User user) {
        LoginDTO loginDTO = userService.register(user);
        return Result.success(loginDTO);
    }

    /**
     * 用户登录
     *
     * @param request 登录请求对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginDTO> login(@RequestBody LoginRequest request) {
        LoginDTO loginDTO = userService.login(request);
        return Result.success(loginDTO);
    }

    /**
     * 用户信息分页查询
     *
     * @param page     分页页码
     * @param pageSize 分页大小
     * @param name     查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    public Result<Page<User>> page(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false, defaultValue = "") String name) {
        log.info("page:{}, pageSize:{}, name:{}", page, pageSize, name);
        //构造分页构造器
        Page<User> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 指定查询的字段
        queryWrapper.select("id", "username", "phone", "role", "createtime", "updatetime");
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), "username", name);
        //添加排序条件
        queryWrapper.orderByDesc("id");
        //执行查询
        userService.page(pageInfo, queryWrapper);

        return Result.success(pageInfo);
    }
}
